package com.hbnu.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbnu.mapper.LoginMapper;
import com.hbnu.pojo.LoginRequest;
import com.hbnu.pojo.User;
import com.hbnu.pojo.WeChatLoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class LoginService {
    
    @Autowired
    private LoginMapper loginMapper;
    
    @Value("${wechat.appid:your_app_id}")
    private String appId;
    
    @Value("${wechat.secret:your_app_secret}")
    private String secret;
    
    /**
     * 微信登录
     */
    public Map<String, Object> wechatLogin(LoginRequest loginRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("[LoginService] 开始微信登录流程");
            System.out.println("[LoginService] 登录请求参数: " + JSON.toJSONString(loginRequest));
            System.out.println("[LoginService] 配置的AppID: " + appId);
            System.out.println("[LoginService] 配置的Secret: " + (secret != null ? secret.substring(0, Math.min(8, secret.length())) + "..." : "null"));
            
            // 1. 调用微信code2Session接口
            WeChatLoginResponse weChatResponse = com.hbnu.utils.WeChatUtil.code2Session(appId, secret, loginRequest.getJsCode());
            
            System.out.println("[LoginService] 微信API调用完成");
            System.out.println("[LoginService] 响应结果: " + JSON.toJSONString(weChatResponse));
            
            if (!weChatResponse.isSuccess()) {
                System.err.println("[LoginService] 微信登录失败 - errcode: " + weChatResponse.getErrcode() + ", errmsg: " + weChatResponse.getErrmsg());
                result.put("success", false);
                result.put("message", "微信登录失败: " + weChatResponse.getErrmsg());
                result.put("errcode", weChatResponse.getErrcode());
                result.put("debug_info", "AppID: " + appId + ", JsCode前缀: " + (loginRequest.getJsCode() != null ? loginRequest.getJsCode().substring(0, Math.min(10, loginRequest.getJsCode().length())) : "null"));
                return result;
            }
            
            String openid = weChatResponse.getOpenid();
            String sessionKey = weChatResponse.getSessionKey();
            
            // 2. 查询用户是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid", openid);
            User existingUser = loginMapper.selectOne(queryWrapper);
            
            User user;
            if (existingUser != null) {
                // 用户已存在，更新登录时间和session_key
                existingUser.setSessionKey(sessionKey);
                existingUser.setLastLoginTime(LocalDateTime.now());
                
                // 如果有新的用户信息，更新
                if (StringUtils.hasText(loginRequest.getUsername())) {
                    existingUser.setUsername(loginRequest.getUsername());
                }
                if (StringUtils.hasText(loginRequest.getAvatarUrl())) {
                    existingUser.setAvatarUrl(loginRequest.getAvatarUrl());
                }
                // unionid字段已移除，不再设置
                
                loginMapper.updateById(existingUser);
                user = existingUser;
            } else {
                // 新用户，创建用户记录
                user = new User(openid, sessionKey);
                // unionid字段已移除，不再设置
                user.setUsername(loginRequest.getUsername());
                user.setAvatarUrl(loginRequest.getAvatarUrl());
                
                loginMapper.insert(user);
            }
            
            // 3. 处理加密数据（如果有）
            if (StringUtils.hasText(loginRequest.getEncryptedData()) && StringUtils.hasText(loginRequest.getIv())) {
                String decryptedData = com.hbnu.utils.WeChatUtil.decryptData(
                    loginRequest.getEncryptedData(), 
                    sessionKey, 
                    loginRequest.getIv()
                );
                
                if (decryptedData != null) {
                    // 解析解密后的用户信息
                    Map<String, Object> userInfo = JSON.parseObject(decryptedData, Map.class);
                    
                    // 更新用户信息
                    if (userInfo.containsKey("nickName")) {
                        user.setUsername((String) userInfo.get("nickName"));
                    }
                    if (userInfo.containsKey("avatarUrl")) {
                        user.setAvatarUrl((String) userInfo.get("avatarUrl"));
                    }
                    
                    loginMapper.updateById(user);
                }
            }
            
            // 4. 生成自定义token（简单示例，实际项目建议使用JWT）
            String token = generateToken(user.getUserId());
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("token", token);
            result.put("user", user);
            
        } catch (Exception e) {
            System.err.println("[LoginService] 登录过程中发生异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            System.err.println("[LoginService] 异常堆栈跟踪:");
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "登录失败: " + e.getMessage());
            result.put("exception_type", e.getClass().getSimpleName());
            result.put("debug_info", "AppID: " + appId + ", JsCode: " + (loginRequest != null && loginRequest.getJsCode() != null ? loginRequest.getJsCode().substring(0, Math.min(10, loginRequest.getJsCode().length())) + "..." : "null"));
            return result;
        }
        
        return result;
    }
    
    /**
     * 生成简单token（实际项目建议使用JWT）
     */
    private String generateToken(Long userId) {
        return "token_" + userId + "_" + UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 根据openid查询用户
     */
    public User getUserByOpenid(String openid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return loginMapper.selectOne(queryWrapper);
    }
    
    /**
     * 更新用户信息（用户名和头像）
     */
    public User updateUserInfo(String openid, String username, String avatarUrl) {
        System.out.println("[LoginService] updateUserInfo called");
        System.out.println("[LoginService] openid: " + openid);
        System.out.println("[LoginService] username: " + username);
        System.out.println("[LoginService] avatarUrl: " + avatarUrl);
        
        try {
            // 根据openid查找用户
            User user = getUserByOpenid(openid);
            if (user == null) {
                System.out.println("[LoginService] User not found for openid: " + openid);
                throw new RuntimeException("用户不存在");
            }
            
            // 更新用户信息
            user.setUsername(username);
            user.setAvatarUrl(avatarUrl);
            user.setLastLoginTime(LocalDateTime.now());
            
            // 保存到数据库
            int updateResult = loginMapper.updateById(user);
            System.out.println("[LoginService] 数据库更新结果: " + updateResult);
            
            if (updateResult > 0) {
                System.out.println("[LoginService] 用户信息更新成功");
                return user;
            } else {
                System.err.println("[LoginService] 数据库更新失败");
                throw new RuntimeException("数据库更新失败");
            }
            
        } catch (Exception e) {
            System.err.println("[LoginService] 更新用户信息异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}
